package com.smart.campus.web.controller.school;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.smart.campus.school.domain.Student;
import com.smart.campus.school.service.IStudentService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.DutyTable;
import com.smart.campus.school.service.IDutyTableService;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;

/**
 * 值日Controller
 * 
 * @author Zhihe.Li
 * @date 2021-06-29
 */
@Controller
@RequestMapping("/school/table")
public class DutyTableController extends BaseController
{
    private String prefix = "school/table";

    @Autowired
    private IDutyTableService dutyTableService;

    @Autowired
    private IStudentService studentService;

    @GetMapping()
    public String table(Long classId, ModelMap mmap)
    {
        mmap.put("classId",classId);
        return prefix + "/table";
    }

    /**
     * 查询值日列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DutyTable dutyTable)
    {
        startPage();
        List<DutyTable> list = dutyTableService.selectDutyTableList(dutyTable);
        List<Student> students = studentService.getStudentByClassIdList(Lists.newArrayList(dutyTable.getClassId()));
        Map<Long,Student> map = students.stream().collect(Collectors.toMap(student-> student.getId(),s->s));
        for (DutyTable table : list) {
            String[] memberIds = table.getMembersIds().split(",");
            StringBuilder membersNames = new StringBuilder("[ ");
            for (String memberId : memberIds) {
                membersNames.append(map.get(Long.valueOf(memberId)).getStudentName() +" ");
            }
            membersNames.append("]");

            table.setLeaderName(map.get(table.getLeaderId()).getStudentName());
            table.setMembersNames(membersNames.toString());
        }


        return getDataTable(list);
    }

    /**
     * 导出值日列表
     */
    @Log(title = "值日", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DutyTable dutyTable)
    {
        List<DutyTable> list = dutyTableService.selectDutyTableList(dutyTable);
        ExcelUtil<DutyTable> util = new ExcelUtil<DutyTable>(DutyTable.class);
        return util.exportExcel(list, "table");
    }

    /**
     * 新增值日
     */
    @GetMapping("/add")
    public String add(Long classId, ModelMap mmap)
    {
        List<Student> students = studentService.getStudentByClassIdList(Lists.newArrayList(classId));
        mmap.put("classId",classId);
        mmap.put("students",students);
        return prefix + "/add";
    }

    /**
     * 新增保存值日
     */
    @Log(title = "值日", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DutyTable dutyTable)
    {
        if(isExist(dutyTable)){
            return AjaxResult.error("当前星期已存在.");
        }
        return toAjax(dutyTableService.insertDutyTable(dutyTable));
    }

    /**
     * 修改值日
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        DutyTable dutyTable = dutyTableService.selectDutyTableById(id);
        List<Student> students = studentService.getStudentByClassIdList(Lists.newArrayList(dutyTable.getClassId()));
        String[] memberIds = dutyTable.getMembersIds().split(",");
        for (String memberId : memberIds) {
            for (Student student : students) {
                if(student.getId().toString().equals(memberId)){
                    student.setSelected(true);
                }
            }
        }

        mmap.put("dutyTable", dutyTable);
        mmap.put("students",students);
        return prefix + "/edit";
    }

    /**
     * 修改保存值日
     */
    @Log(title = "值日", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(DutyTable dutyTable)
    {
        if(isExist(dutyTable)){
            return AjaxResult.error("当前星期已存在.");
        }
        return toAjax(dutyTableService.updateDutyTable(dutyTable));
    }

    /**
     * 删除值日
     */
    @Log(title = "值日", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(dutyTableService.deleteDutyTableByIds(ids));
    }

    /**
     * 校验当前星期是否存在
     * @param dutyTable
     * @return
     */
    private boolean isExist(DutyTable dutyTable){
        DutyTable table = new DutyTable();
        table.setClassId(dutyTable.getClassId());
        table.setWeekDay(dutyTable.getWeekDay());
        List<DutyTable> list = dutyTableService.selectDutyTableList(table);
        if(dutyTable.getId() == null){
            //新增
            return CollectionUtils.isNotEmpty(list);
        }else {
            //修改
            return CollectionUtils.isNotEmpty(list) && !dutyTable.getId().equals(list.get(0).getId());
        }
    }
}
